package com.fire.eyes.service.MyManagementService;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.CkeckTokenService;
import com.fire.core.util.AjaxResult;
import com.fire.eyes.constants.ErrorCodeConstants;
import com.fire.eyes.model.*;
import com.fire.eyes.service.*;
import com.fire.eyes.validation.GetMybuildingDetailDTO;
import com.fire.eyes.validation.TokenDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yangxiaotian
 * @version 1.0
 * @date 2019/1/19 17:34
 * @description:
 */
@Service
public class ManagementService {
    private final static Logger blogin = Logger.getLogger(ManagementService.class);
    @Autowired
    private CkeckTokenService ckeckTokenService;
    @Autowired
    private IUserAuthorityService iUserAuthorityService;
    @Autowired
    private IFireSupervisorUserService iFireSupervisorUserService;
    @Autowired
    private IBuildingService buildingService;
    @Autowired
    private IBuildingTententService buildingTententService;
    @Autowired
    private IBuildingZoneService iBuildingZoneService;

    /**
     * @author yangxiaotian
     * @date ${DATE} ${TIME}
     * @description:通过用户id 获取建筑物list
     */
    public AjaxResult myBuildingList(TokenDTO tokenDTO) {
        AjaxResult result = new AjaxResult();
        try {
            TMitUserToken token = ckeckTokenService.ckeckToken(tokenDTO.getToken());
            if (token == null) {
                blogin.error("ManagementService.myMaitainors().error  错误为：无token记录");
                return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "无token记录", "无token记录");
            }
            Integer userId =token.getUserid();
            UserAuthorityModel userAuthority = iUserAuthorityService.selectOne(new EntityWrapper<UserAuthorityModel>().eq("userid", userId));
            String suthority = userAuthority.getAuthority();
            // 监管单位,
            result = findByAuthority(suthority, userId, tokenDTO);
        } catch (Exception e) {
            e.printStackTrace();
            blogin.error("ManagementService.sitelist().error  错误为：" + e);
            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "服务器开小差", "服务器开小差");
        }
        return result;
    }
    /**
     * @author yangxiaotian
     * @date ${DATE} ${TIME}
     * @description:根据用户ID，查询出监管单位id ,再去建筑物表查询
     *
     */
    public AjaxResult findByAuthority(String suthority, Integer userId, TokenDTO tokenDTO) {
        AjaxResult result = new AjaxResult();
        // 监管单位
        String supervisorStr = "supervisor";
        if (!supervisorStr.equals(suthority)) {
            return new AjaxResult(ErrorCodeConstants.SUCCESS, "操作成功,此用户非 监管单位", "", "操作成功,此用户非 监管单位");
        }
        Wrapper<FireSupervisorUserModel> supervisorUserWrapper = new EntityWrapper<>();
        supervisorUserWrapper.eq("userid", userId);
        FireSupervisorUserModel supervisorUser = iFireSupervisorUserService.selectOne(supervisorUserWrapper);
        String supervisor=null;
        if (supervisorUser!=null){
            supervisor = supervisorUser.getSupervisor();
            if (StringUtils.isBlank(supervisor)) {
                //监管单位ID
                return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "监管单位ID不存在", "监管单位ID不存在");
            }
        }
        //获取监管单位都ID，到建筑物表里面去查
        //判断查询条件
        int page = tokenDTO.getPage();
        int pageSize = tokenDTO.getPagesize();
        List<BuildingModel> list = null;
        if (page == 0 || pageSize == 999) {
            list = buildingService.selectList(new EntityWrapper<BuildingModel>().eq("supervisor", supervisor));
        } else {
            Page<BuildingModel> pages = new Page(tokenDTO.getPage(), tokenDTO.getPagesize());
            Wrapper<BuildingModel> wrapper = new EntityWrapper<>();
            wrapper.eq("supervisor", supervisor);
            Page<BuildingModel> buildingModel = buildingService.selectPage(pages, wrapper);
            if (buildingModel != null) {
                list = buildingModel.getRecords();
            }
        }

        if (list.size() > 0) {
            List<MybuildingListResp> buildinglist = new ArrayList<MybuildingListResp>();
            for (BuildingModel buildingModel : list) {
                MybuildingListResp responsp = new MybuildingListResp();
                responsp.setAddress(buildingModel.getAddress());
                responsp.setBuildingid(buildingModel.getBuldingid());
                responsp.setBuildingname(buildingModel.getBuildingname());
                BuildingZoneModel zoneModel=iBuildingZoneService.selectOne(new EntityWrapper<BuildingZoneModel>().eq("buildingid",buildingModel.getBuldingid()));
               if(zoneModel!=null){
                   responsp.setHousenumber(zoneModel.getHousenumber());//门牌
               }
                responsp.setLatitude(buildingModel.getLatitude());
                responsp.setLongitude(buildingModel.getLongitude());
                buildinglist.add(responsp);
            }
            result.setContext(buildinglist);
            result.setStatus("0");
            result.setTips("查询建筑物成功");
            result.setMessage("查询建筑物成功");

        } else {
            result.setStatus("-1");
            result.setTips("查询建筑物成功，该监管单位暂无建筑物信息");
            result.setMessage("查询建筑物成功，该监管单位暂无建筑物信息");

        }
        return result;

    }
    /**
     * @author yangxiaotian
     * @date ${DATE} ${TIME}
     * @description:获取建筑物详情
     *
     */
    public AjaxResult buildingDetails(GetMybuildingDetailDTO getMybuildingDetailDTO){
//        TMitUserToken token = ckeckTokenService.ckeckToken(getMybuildingDetailDTO.getToken());
//        if (token == null) {
//            blogin.error("ManagementService.myMaitainors().error  错误为：无token记录");
//            return new AjaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "无token记录", "无token记录");
//        }
        AjaxResult result=new AjaxResult();
        BuildingModel buildingModel= buildingService.selectById(getMybuildingDetailDTO.getBuildingid());
        MyBuildingDetailResp resp = new MyBuildingDetailResp();
        if (buildingModel!=null){
            resp.setBuildingid(buildingModel.getBuldingid());
            resp.setBuildingname(buildingModel.getBuildingname());
            resp.setLongitude(buildingModel.getLongitude());
            resp.setLatitude(buildingModel.getLatitude());
            resp.setProvince(buildingModel.getProvince());
            resp.setCity(buildingModel.getCity());
            resp.setZone(buildingModel.getZone());
            resp.setDistrict(buildingModel.getDistrict());
            resp.setAddress(buildingModel.getAddress());
            resp.setBuildimageurl(buildingModel.getBuildimageurl());
        }
        List<BuildingTententModel>list= buildingTententService.selectList(new EntityWrapper<BuildingTententModel>().eq("buildingid",getMybuildingDetailDTO.getBuildingid()));
        BuildingZoneModel zoneModel=iBuildingZoneService.selectOne(new EntityWrapper<BuildingZoneModel>().eq("buildingid",buildingModel.getBuldingid()));
        if(zoneModel!=null){
            resp.setPhone(zoneModel.getTelephone());//电话，
            resp.setHousenumber(zoneModel.getHousenumber());//门牌
        }
        resp.setTententnum(String.valueOf(list.size()));//租户数目
        result.setContext(resp);
        result.setStatus("0");
        result.setTips("查询建筑物详情成功");
        result.setMessage("查询建筑物详情成功");


        return result;
    }

}
